#include <ctype.h>
#ifdef _DEBUG
#include <stdio.h>
#endif
#include <string.h>

#include "resume_parse.h"

static void
ord_insert(const struct field_data *src_arr, struct field_data *out_arr,
		unsigned n)
{
	int elems = 1;
	out_arr[0] = src_arr[0];
	int j;
	for (unsigned i = 1; i < n; ++ i) {
		for (j = 0; j < elems; ++ j)
			if (src_arr[i].data_start < out_arr[j].data_start)
				break;
		if (j != elems)
			memmove(out_arr + j + 1, out_arr + j, (elems - j) *
					sizeof(struct field_data));
		out_arr[j] = src_arr[i];
		elems ++;
	}
}

static void
strip_char_array(char **left, char **right)
{
	char *lp = *left;
	char *rp = *right;
	if (lp == rp)
		return;
	while (isspace(*lp)) {
		++ lp;
		if (lp == rp)
			return;
	}
	while (isspace(*rp))
		-- rp;
	*left = lp;
	*right = rp;
}

enum search_result
keys_search(const char *markup, struct key_search *query)
{
	for (int ck = 0; ck < query->k_count; ++ ck) {
		query->fld_srch[ck].data_start =
				strstr(markup, query->key_names[ck]);
		if (!query->fld_srch[ck].data_start) {
#ifdef _DEBUG
			fprintf(stderr, "warning: key \"%s\" not found\n",
					query->key_names[ck]);
#endif
			return SRCH_NO_KEY;
		} else {
			query->fld_srch[ck].key_id = ck;
		}
		query->fld_srch[ck].data_end = NULL;
	}
	ord_insert(query->fld_srch, query->sorted, query->k_count);

	for (int k = 0; k < query->k_count - 1; ++ k) {
		query->sorted[k].data_start +=
			strlen(query->key_names[query->sorted[k].key_id]);
		query->sorted[k].data_end =
			query->sorted[k + 1].data_start - 1;
		strip_char_array(&(query->sorted[k].data_start),
				&(query->sorted[k].data_end));
	}
	
	query->sorted[query->k_count - 1].data_start +=
	strlen(query->key_names[query->sorted[query->k_count - 1].key_id]);
	
	query->sorted[query->k_count - 1].data_end =
		strchr(query->sorted[query->k_count - 1].data_start, '\0') - 1;
	strip_char_array(&(query->sorted[query->k_count - 1].data_start),
			&(query->sorted[query->k_count - 1].data_end));
	for (int i = 0; i < query->k_count; ++ i) {
		query->res_dict[query->sorted[i].key_id].beginptr =
			query->sorted[i].data_start;
		query->res_dict[query->sorted[i].key_id].endptr =
			query->sorted[i].data_end;
	}
	return SRCH_DONE;
}

